package com.cooldatasoft.web.cms.person;

import java.io.File;

import javax.servlet.ServletContext;

import org.apache.wicket.MarkupContainer;
import org.apache.wicket.extensions.ajax.markup.html.form.upload.UploadProgressBar;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.image.ContextImage;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.Model;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.util.file.Files;
import org.apache.wicket.util.file.Folder;
import org.apache.wicket.util.lang.Bytes;

import com.cooldatasoft.app.WOCApplication;

public class UploadPage extends WebPage {

	MarkupContainer imageDiv;
	ContextImage personImage;
	String imagePath;
	FeedbackPanel feedbackPanel;
	
	public UploadPage(String fileName){
		
		imageDiv = new WebMarkupContainer("imageDiv");		
		
		if(fileName != null && fileName.trim().length()>0){
			imagePath = fileName;
		}else{
			imagePath = "test2.jpg";
		}
		personImage = new ContextImage("personImage",new Model( "img/person/"+imagePath));
//		personImage.setOutputMarkupId(true);
		
		imageDiv.add(personImage);
		ImageUploadForm imageUploadForm = new ImageUploadForm("imageUploadForm");
		imageDiv.add(imageUploadForm);


		add(imageDiv);
	}
	public UploadPage(){
		this(null);
	}
	
	/**
	 * Used for uploading images to system.
	 * @author fatih mehmet ucar
	 *
	 */
	class ImageUploadForm extends Form {

		private FileUploadField fileUploadField;
		private FeedbackPanel uploadFeedback;
		private UploadProgressBar uploadProgressBar;
		
		public ImageUploadForm(String name) {
			super(name);
			
			setMultiPart(true);
			setMaxSize(Bytes.kilobytes(WOCApplication.MAX_FILE_SIZE_KB));
			
			fileUploadField = new FileUploadField("fileInput");
			uploadFeedback = new FeedbackPanel("uploadFeedback");
			// Add upload form with ajax progress bar
			uploadProgressBar = new UploadProgressBar("progress",this);
			
			feedbackPanel = uploadFeedback;
			
			add(fileUploadField);
			add(uploadProgressBar);
			add(uploadFeedback);
		}

		/**
		 * Check if there is already a file with same name. 
		 * @param newFile
		 */
		private void checkFileExists(File newFile) {
			if (newFile.exists()) {
				if (!Files.remove(newFile)) {
					throw new IllegalStateException("Unable to overwrite "+ newFile.getAbsolutePath());
				}
			}
		}

		private Folder getUploadFolder() {
			ServletContext context = ((WebApplication) getApplication()).getServletContext(); 
			File imgFolder = new File(context.getRealPath("/img/person/")); 
			
			if(!imgFolder.exists()){
				imgFolder.mkdirs();
			}
			
			return new Folder(imgFolder);
		}

		protected void onSubmit() {
			final FileUpload upload = fileUploadField.getFileUpload();
			if (upload != null) {
				// Create a new file
				File newFile = new File(getUploadFolder(), upload.getClientFileName());

				// Check new file, delete if it already exists
				checkFileExists(newFile);
				try {
					// Save to new file
					newFile.createNewFile();
					upload.writeTo(newFile);
					imagePath = newFile.getName();
					
				} catch (Exception e) {
					e.printStackTrace();
					uploadFeedback.error("An error occured. Please try again.");
				}
				uploadFeedback.info("Uploaded file : "+ upload.getClientFileName()+" will not be saved until you save person!");
				setResponsePage(new UploadPage(imagePath));
			}
		}
	}
}
